package org.example.backend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.backend.bean.UserBase;
import org.example.backend.mapper.UserBaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 啊昌
 * @date 2025/7/19 10:22
 * MyUserDetailsService security认证
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
	private Logger logger = LoggerFactory.getLogger("com.mjduan.sl4j.logger");

	@Autowired
	private UserBaseMapper userBaseMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserBase user = userBaseMapper.selectOne(new QueryWrapper<UserBase>().eq("username", username));
		if(user == null) {
			// 用户名不存在
			throw new UsernameNotFoundException("用户名不存在");
		}

		// 添加{noop}前缀，告诉Spring使用NoOpPasswordEncoder
//		String password = "{noop}" + user.getPassword();
//		logger.info("用户名: " + username + ", 密码: " + password);

		//todo 这里可以校验用户的权限
		List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
		return new User(user.getUsername(), user.getPassword(), roles);
	}
}
